<template>
  <div class="register">
    <el-form  ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
      <h3 class="title">{{ title }}</h3>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" type="text" auto-complete="off" placeholder="手机号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="registerForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 60%"
          maxlength="4"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
        </el-input>
        <div class="register-code">
          <img :src="codeUrl" @click="getCode" class="register-code-img"/>
        </div>
      </el-form-item>


      <el-form-item prop="msgCode" v-if="captchaEnabled">
        <el-input
          v-model="registerForm.msgCode"
          auto-complete="off"
          placeholder="短信验证码"
          style="width: 60%"
          maxlength="6"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
        </el-input>
        <div class="msg-code">
          <el-button
            size="medium"
            type="primary"
            style="width:100%;"
            @click="handleMesCode"
          >
            <span class="msg-text"> {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}</span>
          </el-button>
        </div>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          auto-complete="off"
          placeholder="确认密码"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>


      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click="handleRegister"
        >
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right;font-size: 16px;width:100%;padding-top: 20px">
       <el-button type="primary" style="width:100%;"> <router-link  style="width:100%;" :to="'/login'">使用已有账户登录</router-link></el-button>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-register-footer">
      <div>Copyright © 2009-2025 程琢教育 All Rights Reserved.</div>
      <div>备案编号：苏ICP备2025174757号</div>
    </div>
  </div>
</template>

<script>
import {getCodeImg, register, getMsgCode, checkRefereeUser} from "@/api/login"
import {MessageBox} from "element-ui";


export default {
  name: "Register",

  watch: {
    $route: {
      handler: function (route) {
        this.registerForm.refereeUser = route.query.u;
        this.registerForm.channel = route.query.c;
      },
      immediate: true
    }
  },

  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"))
      } else {
        callback()
      }
    }
    return {
      countdown: 0,
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      registerForm: {
        refereeUser:null,
        username: "",
        password: "",
        confirmPassword: "",
        code: "",
        uuid: "",
        msgCode: "",
        channel:''
      },
      registerRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的手机号"},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"},
          {min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur"},
          {pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur"}
        ],
        confirmPassword: [
          {required: true, trigger: "blur", message: "请再次输入您的密码"},
          {required: true, validator: equalToPassword, trigger: "blur"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}],
        msgCode: [{required: true, trigger: "change", message: "请输入短信验证码"}]
      },
      loading: false,
      loadingMsg: false,
      captchaEnabled: true
    }
  },
  created() {
    this.getCode()
    this.checkRefereeUser()

  },
  methods: {
    checkRefereeUser() {
      checkRefereeUser(this.registerForm.refereeUser).then((res) => {
        if (res.data !== "success") {

          MessageBox.confirm('二维码已过期！请重新扫码！', '安全提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            closeOnClickModal:false,
            showClose:false,
            type: 'warning'
          }).then(() => {
            this.$router.push({path: "/"}).catch(() => {})
          }).catch(() => {
          })
        }
      }).catch(() => {
        MessageBox.confirm('二维码已过期！请重新扫码', '安全提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
          this.$router.push({path: "/"}).catch(() => {})
        }).catch(() => {
        })
      })
    },

    // 获取短信
    handleMesCode() {
      this.$refs.registerForm.validateField(['username'], valid => {
        if (!valid) {
          this.$refs.registerForm.validateField(['code'], valid => {
            if (!valid) {
              getMsgCode(this.registerForm).then(res => {
                if (res.code === 200) {
                  this.startCountdown(60);
                } else {
                  this.getCode()
                }
              })
            }
          })

        }

      })
    },
    startCountdown(seconds) {
      this.countdown = seconds;
      const intervalId = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown -= 1;
        } else {
          clearInterval(intervalId);
        }
      }, 1000);
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.registerForm.uuid = res.uuid
        }
      })
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          register(this.registerForm).then(res => {
            const username = this.registerForm.username
            this.$alert("<font color='red'>恭喜你，您的账号 " + username + " 注册成功！</font>", '系统提示', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            }).then(() => {
              let loginForm ={}
              loginForm.username = this.registerForm.username
              loginForm.password = this.registerForm.password
              this.$store.dispatch("Login", loginForm).then(() => {
                console.log(this.$store.getters)
                const userType = this.$store.getters.userType
                if (userType === '20') {
                  console.log(1)
                  this.$router.push({path: "/kaoshi/shouye"}).catch(() => {})
                } else {
                  console.log(2)
                  this.$router.push({path: "/"}).catch(() => {})
                }

              }).catch(() => {
                this.loading = false
                if (this.captchaEnabled) {
                  this.getCode()
                }
              })

            }).catch(() => {
            })
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.register {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
z-index: 20;
  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.register-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.msg-code {
  width: 116px;
  height: 38px;
  float: right;
}

.msg-text {
  margin-left: -10px;
}

.el-register-footer {
  height: 80px;
  line-height: 30px;
  position: absolute;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  z-index: 0;
}

.register-code-img {
  height: 38px;
  width: 116px;
}
</style>
